# -*-coding: utf-8 -*-
import os
import csv
import socket
import pymysql
import configparser
import tkinter as tk
from tkinter import ttk
from loguru import logger
from datetime import datetime
from tkinter import messagebox
from tkcalendar import DateEntry



# 指定日志文件的路径和名称
log_file_path = "./logs/gms_tools.log"

# 确认 log 文件夹存在
log_folder = os.path.dirname(log_file_path)
if not os.path.exists(log_folder):
    os.makedirs(log_folder)


logger.add(log_file_path)

class GmsTools:
    def __init__(self, root):
        logger.info("打开GMS工具")
        self.root = root
        self.root.title("GMS工具V1.2.0")
        self.root.geometry("800x500")
        self.root.resizable(width=False, height=False)

        self.page = 1
        self.page_size = 15
        self.status = "总记录数: 0    "

        # 查询条件
        self.start_date_var = tk.StringVar()
        self.end_date_var = tk.StringVar()

        # 查询结果
        self.tree = None

        # 配置数据库
        self.db_conf()

        self.conn = pymysql.connect(host=self.host, user=self.user, port=int(self.port), password=self.password, database=self.database)
        self.cursor = self.conn.cursor()

        self.create_widgets()

        # 用户使用信息
        self.pc_host = socket.gethostname()
        self.pc_user = os.environ['USERNAME']
        self.pc_ip = socket.gethostbyname(self.host)
        self.pc_info = "LogIn"
        self.pc_login_time = datetime.now()
        self.pc_logout_time = None
        self.record_user_info()

    
    def __del__(self):
        self.pc_info = "LogOut"
        self.pc_logout_time = datetime.now()
        self.record_user_info()
        self.close_db()
        logger.info("退出GMS工具")


    def db_conf(self):
        config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'conf/config.ini')
        config = configparser.ConfigParser()
        config.read(config_file)
        self.host = config.get('1001', 'host')
        self.user = config.get('1001', 'user')
        self.port = config.get('1001', 'port')
        self.password = config.get('1001', 'password')
        self.database = config.get('1001', 'database')


    def create_widgets(self):
        # 查询条件
        label1 = tk.Label(self.root, text="开始时间:")
        label1.place(x=10, y=10)
        start_date = DateEntry(self.root, width=12, background='darkblue', foreground='white', date_pattern='yyyy-mm-dd', textvariable=self.start_date_var)
        start_date.place(x=80, y=10)

        label2 = tk.Label(self.root, text="结束时间:")
        label2.place(x=220, y=10)
        end_date = DateEntry(self.root, width=12, background='darkblue', foreground='white', date_pattern='yyyy-mm-dd', textvariable=self.end_date_var)
        end_date.place(x=290, y=10)


        self.pid_label = tk.Label(self.root, text="角色账号:")
        self.pid_label.place(x=10, y=50)
        self.pid_entry = tk.Entry(self.root, width=18)
        self.pid_entry.place(x=70, y=50)

        self.server_label = tk.Label(self.root, text="服务器ID:")
        self.server_label.place(x=220, y=50)
        self.server_entry = tk.Entry(self.root, width=18)
        self.server_entry.place(x=280, y=50)


        self.order_label = tk.Label(self.root, text="充值订单:")
        self.order_label.place(x=450, y=50)
        self.order_entry = tk.Entry(self.root, width=18)
        self.order_entry.place(x=510, y=50)

        export_button = tk.Button(self.root, text="导出CSV", command=self.export_csv)
        export_button.place(x=700, y=7)

        query_button = tk.Button(self.root, text="查询数据", command=self.query_data)
        query_button.place(x=700, y=45)

        version_label = tk.Label(self.root, text="GMS©2023", fg="blue")
        version_label.place(x=705, y=470)

    def query_data(self):
        # 2022-02-14 19:20:19
        start_date = self.start_date_var.get() + " 00:00:00"
        end_date = self.end_date_var.get() + " 23:59:59"

        server = self.server_entry.get()
        pid = self.pid_entry.get()
        order = self.order_entry.get()

        query_sql = "SELECT id, order_id, server_id, pay_user,player_name, pay_ip, pay_amount, pay_gold, last_time FROM pay_action WHERE 1=1 "

        params = []
        if server != "":
            query_sql += f" AND server_id = %s "
            params.append(server)
        if pid != "":
            query_sql += f" AND pay_user = %s "
            params.append(pid)
        if order != "":
            query_sql += f" AND order_id = %s "
            params.append(order)

        query_sql += f" AND last_time BETWEEN %s AND %s"
        params.append(start_date)
        params.append(end_date)

        try:
            count_query = f"select * from pay_action where last_time BETWEEN %s AND %s"
            self.cursor.execute(count_query, (start_date, end_date))
            count = self.cursor.fetchall()
            if count:
                self.total_rows = len(count)
                self.status = f"总记录数: {self.total_rows}"
    
            start_index = (self.page - 1) * self.page_size
            query_sql += f" LIMIT %s, %s"
            params.append(start_index)
            params.append(self.page_size)

            logger.info(query_sql, params)
            self.cursor.execute(query_sql, params)
            rows = self.cursor.fetchall()
            self.show_data(rows)
            self.show_status()
        except Exception as e:
            logger.error("查询数据失败:", e)
            messagebox.showerror("查询数据失败", str(e))



    def show_data(self, rows):
        if self.tree:
            self.tree.destroy()

        self.tree = ttk.Treeview(self.root,height=15, columns=("id","order_id", "server_id", "pay_user","player_name", "pay_ip", "pay_amount", "pay_gold", "last_time"))
        self.tree.heading('#0', text='', anchor='w')  # 隐藏第一列的表头
        self.tree.column('#0', width=0, stretch='no')  # 将第一列的宽度设置为0，使其不可见
        self.tree.column("id", width=40,)
        self.tree.column("order_id", width=180,)
        self.tree.column("server_id", width=50)
        self.tree.column("pay_user", width=88)
        self.tree.column("player_name", width=80)
        self.tree.column("pay_ip", width=110)
        self.tree.column("pay_amount", width=50)
        self.tree.column("pay_gold", width=50)
        self.tree.column("last_time", width=130)
        
        self.tree.heading("id", text="ID")
        self.tree.heading("order_id", text="订单")
        self.tree.heading("server_id", text="服务器")
        self.tree.heading("pay_user", text="角色ID")
        self.tree.heading("player_name", text="角色名")
        self.tree.heading("pay_ip", text="IP")
        self.tree.heading("pay_amount", text="金额")
        self.tree.heading("pay_gold", text="货币")
        self.tree.heading("last_time", text="时间")

        self.tree.place(x=10, y=80)
        for row in rows:
            self.tree.insert("", tk.END, values=row)
        
        self.previous_button = tk.Button(self.root, text="上一页", command=self.previous_page)
        self.previous_button.place(x=320, y=425)

        self.page_label = tk.Label(self.root, text=f"第{self.page}页", fg="blue")
        self.page_label.place(x=375, y=430)

        self.page_label.config

        self.next_button = tk.Button(self.root, text="下一页", command=self.next_page)
        self.next_button.place(x=420, y=425)

    def show_status(self):
        self.status_label = tk.Label(self.root, text=self.status, fg="blue")
        self.status_label.place(x=10, y=470)


    def previous_page(self):
        if self.page > 1:
            self.page -= 1
            self.clear_data()
            self.query_data()


    def next_page(self):
        query = "SELECT COUNT(*) FROM pay_action"
        self.cursor.execute(query)
        total_rows = self.cursor.fetchone()[0]
        total_pages = total_rows // self.page_size + (1 if total_rows % self.page_size != 0 else 0)
        if self.page < total_pages:
            self.page += 1
            self.clear_data()
            self.query_data()


    def clear_data(self):
        for row in self.tree.get_children():
            self.tree.delete(row)


    def export_csv(self):
        start_date = self.start_date_var.get() + " 00:00:00"
        end_date = self.end_date_var.get() + " 23:59:59"

        logger.info(start_date, end_date)
        self.label = tk.Label(root, text='', font=('TkDefaultFont', 20))
        self.label.pack(side='bottom', pady=10,padx=3)
        self.label.place(x=450, y=465)

        self.progress_bar = ttk.Progressbar(self.root, orient="horizontal", length=250, mode="determinate")
        self.progress_bar.pack(side='bottom', pady=10,padx=1)
        self.progress_bar.place(x=200, y=470)
        
        if not start_date or not end_date:
            self.progress_bar.stop()
            self.progress_bar.place_forget()
            messagebox.showinfo("提示", "请选择起始日期和结束日期!")
            return

        rows = []
        query_sql = "SELECT * FROM pay_action WHERE pay_status = 4 and last_time BETWEEN %s AND %s"
        self.cursor.execute(query_sql, (start_date, end_date))
        rows.extend(self.cursor.fetchall())
        self.total_rows = len(rows)
        self.show_status()

        if not self.total_rows:
            self.progress_bar.stop()
            self.progress_bar.place_forget()
            logger.info("查询数据为空!")
            messagebox.showinfo("提示", "查询数据为空!")
            return

        file_data = datetime.now().strftime("%Y-%m-%d")

        file_name = f"pay_{file_data}.csv"
        with open(file_name, 'w', newline='', encoding="utf-8") as f:
            writer = csv.writer(f)
            writer.writerow([i[0] for i in self.cursor.description])
            rows_num = len(rows)
            logger.info(f"导出数据:{rows_num}条")
            i = 0
            for row in rows:
                self.progress_bar["value"] = int((i / rows_num) * 100)
                
                self.progress_bar.update() 
                writer.writerow(row)
                if i < rows_num:
                    i += 1
                self.label.config(text=str(int((i / rows_num) * 100)) + "%")  # 更新label的值
        messagebox.showinfo("信息", f"导出CSV文件{file_name}成功!")
        self.progress_bar.stop()
        self.progress_bar.place_forget()  # 隐藏进度条
        # self.progress_bar.destroy()  # 移除进度条 
        self.label.config(text='')

    def record_user_info(self):
        config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'conf/config.ini')
        config = configparser.ConfigParser()
        config.read(config_file)
        host = config.get('1002', 'host')
        user = config.get('1002', 'user')
        port = config.get('1002', 'port')
        password = config.get('1002', 'password')
        database = config.get('1002', 'database')

        conn = pymysql.connect(host=host, user=user, port=int(port), password=password, database=database)
        cursor = conn.cursor()
        sql = """INSERT INTO user_info (host, user, info, ip, login_time, logout_time) VALUES (%s, %s, %s, %s, %s, %s)"""
        cursor.execute(sql, (self.pc_host, self.pc_user, self.pc_info, self.pc_ip, self.pc_login_time, self.pc_logout_time))
        conn.commit()
        cursor.close()
        conn.close()

    def close_db(self):
        self.cursor.close()
        self.conn.close()


root = tk.Tk()
GmsTools(root)
root.mainloop()